Web development and Tech news Blog site. WEBISFREE.com

HOME > lodash

[lodash] Understanding the fromPairs() method

Last Modified : 01 Mar, 2023 / Created : 01 Mar, 2023
473
View Count
Let's take a look at one of the methods in lodash, fromPairs().





# The lodash method fromPairs()


As the name suggests, fromPairs() is a method that creates an object from a pair of values that form a single pair, much like the literal meaning of the word "pair." This means that there must be two values, key and value, that form a pair. For example, when you want to obtain an object from an array that consists of key-value pairs, you can easily convert it to an object using fromPairs().

Next, let's look at the syntax. The usage is very simple:

_.fromPairs(pair)



pair // an array of values consisting of key and value

Now let's take a look at a few examples.

Example 1)
myArray = [[ 'a', 1 ], ['b', 2], ['c', 3]]
myObj = _.fromPairs(myArray)

// Result
{
  a: 1,
  b: 2,
  c: 3
}


Example 2)
myArray = [[ 'no', 1 ], ['sitename', 'WEBISFREE'], ['url', 'webisfree.com']]
myObj = _.fromPairs(myArray)

// Result
{
  no: 1,
  sitename: 'WEBISFREE',
  url: 'webisfree.com'
}


Example 3)
What if the value of the array is an object?
myArray = [[ 'a', {'aa': '2 depths'} ]]
myArray2 = [[ 'a', {'aa': { 'aaa': '3 depths'} } ]]

myObj = _.fromPairs(myArray)
myObj2 = _.fromPairs(myArray2)

If you look at the following result, using an object as a value works without any problems. This means that you can use both primitive and reference values as values.
// Result
{
  a: {
    aa: '2 depths'
  }
}

{
  a: {
    aa: {
      '3 depths'
    }
  }
}


Example 4)
What if each value is represented without using the [] symbol, as in the example below?
myArray = [ 'a', '1' ]
myObj = _.fromPairs(myArray)

// Result
{
  1: undefined,
  a: undefined
}

If you look at the result, all the values are displayed as undefined. This is because each value of the array is recognized as a separate pair, resulting in an object with only keys but no values.

So far, we have looked at the lodash method fromPairs().


! Tip and Tricks


In addition, there is a method in lodash called toPairs() that works similarly to fromPairs(). In fact, toPairs() works completely opposite to fromPairs(). It creates an array from an object rather than creating an object from an array.
Come to think of it, there is a similar method in the built-in methods of arrays, Object.entries(). Shall we take a look at the code?
myArray = Object.entries({a: 1, b: 2, c: 3})
myObj = _.fromPairs(myArray)

// Result
{ a: 1, b: 2, c: 3 }

It would be helpful to know both methods.

Perhaps you're looking for the following text as well?

Previous

Understanding lodash's omitBy() function

Previous

[lodash] How to use the trim() function and examples